import { existsSync, readFileSync, writeFileSync } from 'fs';
import path from 'path';
import { BasePlatform } from '../platforms/BasePlatform';
import { AutoUploadPlatform, channelToName, EPlatform, GAMEPF } from '../platforms/PlatformConfig';
import { DingdingBot } from '../utils/DingdingBot';
import { LogReport } from '../utils/LogReport';
import PackUtil from '../utils/PackUtil';
import { FeishuBot } from '../utils/FeishuBot';
let originPlatformId: number = 1;
export function beforeStartBuild(options: {
    channel: string,//渠道
    projectDir: string,//工程目录
    platformsInfo: any,//渠道信息
    isDebug?: boolean,//是否是测试版本
    bmsName?: string,//强制bmsname
}, callback: Function) {
    //Cocos引擎修改
    if (!PackUtil.isUnityGame) {
        //构建前工作: 修改Launcher.fire的属性
        let launcherscene = path.join(options.projectDir, "assets/scene/Launcher.fire");
        if (existsSync(launcherscene)) {
            let launcher: Object[] = JSON.parse(readFileSync(launcherscene, { encoding: 'utf-8' }));
            for (let i = 0, len = launcher.length; i < len; i++) {
                let obj = launcher[i];
                if (obj.hasOwnProperty('CustomPlatform')) {
                    //@ts-ignore
                    originPlatformId = obj['CustomPlatform'];
                    //@ts-ignore
                    obj['CustomPlatform'] = EPlatform[options.channel];
                    if (obj.hasOwnProperty("testMode")) {
                        //@ts-ignore
                        obj['testMode'] = !!options.isDebug;
                    }

                    if (obj.hasOwnProperty("remoteConfig")) {
                        //@ts-ignore
                        obj['remoteConfig'] = global.remoteConfig;
                    }
                    if (obj.hasOwnProperty("bmsVersion")) {
                        //@ts-ignore
                        obj['bmsVersion'] = global.bmsVersion;
                        //@ts-ignore
                        console.log('global.bmsVersion', obj['bmsVersion'])
                    }
                    writeFileSync(launcherscene, JSON.stringify(launcher, null, "\t\t"), { encoding: 'utf8' });
                    break;
                }

            }
        } else {
            //另外一个配置
            let configtspath = path.join(options.projectDir, "assets/script/config/GConfig.ts");
            if (existsSync(configtspath)) {
                let configts = readFileSync(configtspath, { encoding: 'utf-8' }).toString();
                //@ts-ignore
                let curChannel = GAMEPF[options.channel];
                // if(options.bmsName){
                //     curChannel = options.bmsName;
                //     console.log("强制bms=",curChannel);
                // }
                let newp = configts.replace(/public PF = .*/, `public PF = '${curChannel}';`);
                writeFileSync(configtspath, newp, { encoding: 'utf8' });
            }
        }


        //是否压缩图片
        let compressFire = path.join(options.projectDir, "settings", "ccc-png-auto-compress.json");
        if (existsSync(compressFire)) {
            let compressfile: Object[] = JSON.parse(readFileSync(compressFire, { encoding: 'utf-8' }));
            //@ts-ignore
            compressfile["enabled"] = !!global.isCompress;
            writeFileSync(compressFire, JSON.stringify(compressfile, null, "\t\t"), { encoding: 'utf8' });
        }

        //是否混淆代码
        let ocFire = path.join(options.projectDir, "settings", "ccc-obfuscated-code.json");
        if (existsSync(ocFire)) {
            let ocssfile: Object[] = JSON.parse(readFileSync(ocFire, { encoding: 'utf-8' }));
            //@ts-ignore
            ocssfile["auto"] = !!global.isOc;
            writeFileSync(ocFire, JSON.stringify(ocssfile, null, "\t\t"), { encoding: 'utf8' });
        }

        //排除3D拍模块
        let builder = path.join(options.projectDir, "settings", "project.json");
        if (existsSync(builder) && options.platformsInfo.isNative) {
            let builderFile: any = JSON.parse(readFileSync(builder, { encoding: 'utf-8' }));

            if (builderFile["excluded-modules"]) {
                builderFile["excluded-modules"] = [
                    "3D Physics/Builtin"
                ];
                writeFileSync(builder, JSON.stringify(builderFile, null, "\t\t"), { encoding: 'utf8' });
            }
            console.log(builderFile)
        }
    }

    callback();
}

//机器人通知
export function afterBuildFinish(options: {
    platform: BasePlatform
}, callback: Function) {
    let pl = options.platform;
    let version = pl.version;
    let channelName = channelToName[pl.curPackChannel];
    // let bot = new DingdingBot(pl.configData.dingTalkWebHook);
    let bot = new FeishuBot(pl.configData.feiShuWebHook);
    let gameName = pl.channelInfo.gameName ? pl.channelInfo.gameName : pl.configData.gameName;
    let outputPath: string;

    // 自动上传平台
    if (AutoUploadPlatform[pl.curPackChannel]) {
        outputPath = channelName + "后台";
    }
    // Web平台
    else if (pl.curPackChannel == 'web_mobile' || pl.curPackChannel == 'web_desktop') {
        outputPath = `[${channelName}链接](${pl.channelInfo.serverPath}?_t=${Date.now()})`;
    }
    // 其他平台
    else {
        outputPath = pl.outputPath.substr(2);
    }

    if (pl.curPackChannel == 'oppo' || pl.curPackChannel == 'vivo' || pl.curPackChannel == 'xiaomi' || pl.curPackChannel == 'huawei') {
        outputPath = `${outputPath}\\${pl.channelInfo.platform}\\dist\\`;
    }
    if (pl.curPackChannel.indexOf("ios") != -1 && pl.isDebug) {
        //@ts-ignore
        outputPath = `[${channelName}链接](${pl.QRCodeURL})`;
        //@ts-ignore
        version = `${version}(${pl.buildVersion})`
    }

    //@ts-ignore
    if (pl.configData.notifyDingTalk && pl.configData.dingTalkWebHook && !global.isSkipNotify) {
        let title = `${gameName}打包通知`;
        let msg =
            `**游戏名字：<font color='blue'>${gameName}</font>**
**游戏渠道：${channelName}**
**游戏版本：${version}**
**打包状态：<font color='green'>完成</font>**
**资源包路径：${outputPath}**
**打包时间：${new Date().toLocaleString()}**\n `;
        //@ts-ignore
        let packDesc = global.packDesc;
        if (packDesc != "") {
            msg += `**打包说明：<font color='green'>${packDesc}</font>**\n `;
        }
        //@ts-ignore
        const atUser = global.atUser.split(',').map(String).filter(Boolean);
        bot.pushMsgMarkdown(msg, title, atUser);
    }
    if (pl.configData.logReportUrl) {
        let reporter = new LogReport(pl.configData.logReportUrl);
        let data: any = {};
        data.name = gameName;
        data.version = version;
        data.project_team = pl.configData.teamName;
        data.source_path = outputPath;
        data.build_time = `${Math.round(Date.now() / 1000)}`;
        data.release_channel = channelName;
        if (pl.channelInfo.packageName) {
            data.pkg_name = pl.channelInfo.packageName;
        }
        reporter.postLog(data)
    }
    //构建完成后工作
    callback();
}